package com.application.fabric.水印.盲水印;


import javax.imageio.ImageIO;
import javax.imageio.stream.ImageInputStream;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Arrays;

public class BlindWatermarking {
    public static void main(String[] args) throws Exception{
        /*1.读取图像文件，将图像数据转化为二进制流。可以使用Java的ImageIO.read()方法读取图像文件，将图像转换为BufferedImage格式。[1]*/
        File file = new File("src/test/java/com/application/fabric/水印/test1.jpg");
        BufferedImage image = ImageIO.read(file);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", baos);
        byte[] imageBytes = baos.toByteArray();


        /*水印信息创建*/
        byte[] watermarkBytes = new byte[imageBytes.length];
        String watermsgamin = "hatelys";
        byte[] msg = watermsgamin.getBytes();
        for (int i=0;i<msg.length;i++){
           watermarkBytes[i] = msg[i];
        }


        /*2.将二进制流嵌入水印信息。在最低有效位盲水印中，将水印信息嵌入到图像的最低有效位中，可以使用Java的位运算实现。[3]*/
//        for (int i = 0; i < imageBytes.length; i++) {
//            int bit = (watermarkBytes[i / 8] >> (7 - i % 8)) & 1;
//            imageBytes[i] = (byte) ((imageBytes[i] & 0xFE) | bit);
//        }
//        System.out.println(imageBytes[1]);
        

        /*3.将嵌入水印信息的二进制流转化为图像。可以使用Java的ImageIO.write()方法将二进制流转化为图像文件。[1]*/
        ByteArrayInputStream in = new ByteArrayInputStream(imageBytes);
        BufferedImage imageWithWatermark = ImageIO.read(in);
        if (imageWithWatermark !=null){
            /*创建文件*/
            FileOutputStream outImgStream = new FileOutputStream("src/test/java/com/application/fabric/水印/test3.jpg");
            ImageIO.write(imageWithWatermark, "jpg", outImgStream);
        }else {
            System.out.println("沙比代码出错了");
        }


        /*4.提取图像中的水印信息。对于最低有效位盲水印，可以使用Java的位运算提取图像中的水印信息。[3]*/
        for (int i = 0; i < imageBytes.length; i++) {
            int bit = imageBytes[i] & 1;
            watermarkBytes[i / 8] |= bit << (7 - i % 8);
        }
    }
}
